import React, { PureComponent } from 'react'
import { DndProvider } from 'react-dnd'
import { HTML5Backend } from 'react-dnd-html5-backend'
import list2tree from 'list2tree'
import { history } from '@umijs/max'
import styles from './index.less'
import {
  BreadcrumbBar,
  HufuTreeTitle,
  InputSearch,
  ProTable,
  ProTableOperate,
  ProTableOptions,
  ProTree,
  searchTreeListByName,
} from '@/components'
import { treeThemes } from './api'

const getNavTreeDataFunc = list2tree({
  idKey: 'id',
  parentIdKey: 'pid',
  newKey: {
    key: 'id',
    value: 'id',
    title: 'themeName',
  },
})

const menus = [{ name: '数据质量' }, { name: '监控规则' }]
const { OperateItem } = ProTableOperate

export default class RuleConfig extends PureComponent {
  constructor(props) {
    super(props)
    this.state = {
      columns: [
        {
          title: '表名',
          dataIndex: 'tableName',
          width: '22%',
          key: 'tableName',
        },
        {
          title: '描述',
          dataIndex: 'comment',
          width: '32%',
          key: 'comment',
          render: (text, record) => (!text || text === '' ? '--' : text),
        },
        {
          title: '规则数',
          dataIndex: 'ruleNum',
          width: '22%',
          key: 'ruleNum',
        },
        {
          title: '操作',
          dataIndex: 'operation',
          width: '24%',
          key: 'operation',
          render: (text, record, index) => (
            <ProTableOptions>
              <span onClick={() => {
                history.push(`/dataQuality/ruleConfigSee?tableName=${record.tableName}&tblId=${record.tblId}&hasPartition=${record.hasPartition}`)
              }}
              >配置监控规则
              </span>
            </ProTableOptions>
          ),
        },
      ],
      loading: false,
      treeData: [],
      treeDataNew: [],
      selectedKeys: [],
      query: {},
    }
  }

  componentDidMount() {
    this.getTreeThemes()
  }

  // 获取左侧列表方法
  getTreeThemes() {
    // 标记每个节点是第几层children
    const signLayerNum = (item, num = 0) => {
      item.layerNum = num
      if (num >= 5) {
        item.disabled = true
      }
      if (item.children) {
        item.children.map((child) => {
          const tempNum = num + 1
          signLayerNum(child, tempNum)
        })
      }
    }
    treeThemes().then(
      (res) => {
        const arr = getNavTreeDataFunc(res)
        // 给tree的数据标上第几层children
        arr.map((item) => {
          signLayerNum(item)
        })
        this.setState({
          treeData: res,
          treeDataNew: arr,
        })
      },
      (error) => {
        console.log(error)
      },
    )
  }

  defaultIconFun = props => {
    const { selectedKeys } = this.state
    if (selectedKeys && selectedKeys[0] === props.data.key) {
      return props.expanded ? <i className="iconfont-colour2 icon-wenjianjia-dakaihover" /> : <i className="iconfont-colour2 icon-wenjianjia-morenhover" />
    }
    return props.expanded ? <i className="iconfont-colour2 icon-wenjianjia-dakai" /> : <i className="iconfont-colour2 icon-wenjianjia-moren" />
  }

  renderTreeNodes = (data) => {
    const tempArr = []
    data.map((item) => {
      const {
        title, children, layerNum, ...restProps
      } = item
      const tempObj = {
        icon: layerNum >= 5 ? true : this.defaultIconFun,
        ...restProps,
      }
      if (item.pid !== '0') {
        tempObj.title = (
          <HufuTreeTitle
            title={title}
            key={item.id}
            icon
          />
        )
      } else {
        tempObj.title = (
          <HufuTreeTitle
            title={title}
            key={item.id}
            icon
          />
        )
      }
      if (item.children) {
        tempObj.children = this.renderTreeNodes(item.children)
      }
      tempArr.push(tempObj)
    })
    return tempArr
  }

  onSelect = (selectedKeys) => {
    this.setState({
      selectedKeys,
      query: {
        themeId: selectedKeys[0],
      },
    })
  }

  render() {
    const {
      treeData, treeDataNew, selectedKeys, loading, query, taskName,
    } = this.state
    return (
      <div className={`${styles.page_content_with_breadcrumb} ${styles.theme_design}`}>
        <BreadcrumbBar menu={menus} />
        <div className={styles.page_content}>
          <div className={styles.page_content_left}>
            <ProTree
              showLine
              showSearch
              showTitle={false}
              treeData={treeDataNew}
              renderTreeNodes={this.renderTreeNodes}
              selectedKeys={selectedKeys}
              onSelect={this.onSelect}
              ref={(dev) => (this.tree = dev)}
              search={(name) => {
                const searchTree = searchTreeListByName(
                  name,
                  treeData,
                  'themeName',
                )
                const treeDataNews = getNavTreeDataFunc(
                  searchTree.result,
                )
                this.setState(
                  {
                    treeDataNew: treeDataNews,
                  },
                  () => {
                    this.tree.onExpand(searchTree.fatchIds)
                  },
                )
              }}
            />
          </div>
          <div className={styles.page_content_right}>
            <ProTableOperate
              toggleOperate={false}
              unfolded
            >
              <OperateItem align="left">
                <InputSearch
                  placeholder="请输入数据表名称或者描述进行搜索"
                  value={taskName}
                  onChange={(e) => {
                    this.setState({
                      taskName: e.target.value,
                    })
                  }}
                  onSearch={(e) => {
                    this.setState({
                      query: {
                        tableName: taskName || '',
                      },
                    })
                  }}
                />
              </OperateItem>
            </ProTableOperate>
            <DndProvider backend={HTML5Backend}>
              <ProTable
                url="/api/v1/dataQuality/manager/getTables"
                query={query}
                columns={this.state.columns}
                loading={loading}
              />
            </DndProvider>
          </div>
        </div>
      </div>
    )
  }
}
